package com.data4.supplier.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.data4.feignapi.common.constants.ProductConstants;
import com.data4.feignapi.dto.PageDTO;
import com.data4.feignapi.dto.ProductDTO;
import com.data4.feignapi.dto.ProductPageDTO;
import com.data4.feignapi.dto.Result;
import com.data4.feignapi.entity.Brand;
import com.data4.feignapi.entity.Product;
import com.data4.feignapi.entity.Supplier;
import com.data4.feignapi.vo.ProductBriefVO;
import com.data4.feignapi.vo.ProductDetailVO;
import com.data4.supplier.mapper.ProductMapper;
import com.data4.supplier.service.BrandService;
import com.data4.supplier.service.CategoryService;
import com.data4.supplier.service.ProductService;
import com.data4.supplier.service.SupplierService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Forever
 * @since 2024-12-11
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Resource
    private BrandService brandService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private SupplierService supplierService;

    @Override
    public Result addProduct(ProductDTO productDTO, String supplierId) {
        Product product = BeanUtil.toBean(productDTO, Product.class);
        product.setSupplierId(Integer.parseInt(supplierId));
        boolean save = save(product);
        return save ? Result.ok() : Result.fail("添加失败");
    }

    @Override
    public Result deleteByIds(List<Integer> productIds, String supplierId) {

        boolean remove = remove(new LambdaQueryWrapper<Product>()
                .eq(Product::getSupplierId, Integer.parseInt(supplierId))
                .in(Product::getProductId, productIds));
        return remove ? Result.ok() : Result.fail("删除失败");
    }

    @Override
    public Result updateProduct(ProductDTO productDTO, Integer productId) {
        Product product = BeanUtil.toBean(productDTO, Product.class);
        boolean update = update(product, new LambdaQueryWrapper<Product>()
                .eq(Product::getProductId, productId));
        return update ? Result.ok() : Result.fail("更新失败");
    }

    @Override
    public Result getProduct(Long current, Long num) {
        Page<Product> page = lambdaQuery()
                .orderByAsc(Product::getProductId)
                .select(Product::getProductId, Product::getProductName,
                        Product::getMarketPrice, Product::getModelNumber,
                        Product::getProductImg,
                        Product::getStock, Product::getProductDescription,
                        Product::getSellingPrice, Product::getUnit)
                .page(new Page<>(current, num));
        long total = page.getTotal();
        List<Product> productList = page.getRecords();
        PageDTO pageDTO = new PageDTO();
        List<ProductBriefVO> productBriefVOS = productList
                .stream()
                .map(product -> BeanUtil.toBean(product, ProductBriefVO.class))
                .collect(Collectors.toList());
        pageDTO.setList(productBriefVOS);
        pageDTO.setTotalNum(total);
        return Result.ok(pageDTO);
    }

    @Override
    public Result getProductGroup(List<String> groupIds, Integer supplierId) {
        if (CollUtil.isEmpty(groupIds)) return Result
                .fail("分组查询条件为空,请选择分组条件");
        // 使用 QueryWrapper 构建查询
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        String query = StrUtil.join(",", groupIds);
        query = query + "," + ProductConstants.QUERY_GROUP;
        queryWrapper
                .select(query)
                .eq("supplier_id", supplierId)
                .groupBy(groupIds); // 直接列出分组依据
        List<Map<String, Object>> resultMaps = listMaps(queryWrapper);
        return Result.ok(resultMaps);
    }

    @Override
    public ProductPageDTO getProductByNameLike(String productName, Integer current,
                                       Integer num, Integer supplierId) {
        Page<Product> page = lambdaQuery()
                .eq(supplierId != null, Product::getSupplierId, supplierId)
                .like(Product::getProductName, productName)
                .page(new Page<>(current, num));
        if(page.getTotal()==0) return null;
        ProductPageDTO productPage = new ProductPageDTO();
        productPage.setList(page.getRecords());
        productPage.setTotalNum(page.getTotal());
        return productPage;
    }

    @Override
    public Result getProductByMarkerPriceScope(Integer current, Integer num,
                                               Integer little, Integer big,
                                               Integer supplierId) {
        Page<Product> productPage = lambdaQuery()
                .ge(little.intValue() != -1, Product::getMarketPrice, little * 100)
                .le(big.intValue() != -1, Product::getMarketPrice, big * 100)
                .eq(supplierId != null, Product::getSupplierId, supplierId)
                .page(new Page<>(current, num));
        List<Product> productList = productPage.getRecords();
        PageDTO productPageDTO = new PageDTO();
        productPageDTO.setList(productList);
        productPageDTO.setTotalNum(productPage.getTotal());
        return Result.ok(productPageDTO);
    }

    @Override
    public ProductDetailVO getProductDetail(Integer productId) {
        Product product = lambdaQuery()
                .eq(Product::getProductId, productId)
                .one();
        if (BeanUtil.isEmpty(product)) return null;
        ProductDetailVO productDetailVO = BeanUtil
                .toBean(product, ProductDetailVO.class);
        productDetailVO.setCategoryAndStandardsVO(categoryService
                .getCategoryAndStandardsVO(product.getCategoryId(),null));
        productDetailVO.setBrand(brandService.getOne(new LambdaQueryWrapper<Brand>()
                .eq(Brand::getBrandId, product.getBrandId())));
        productDetailVO.setSupplier(supplierService.getSupplierById(product.getSupplierId()));
        return productDetailVO;
    }

    @Override
    public Result getProductSupplier(Long current, Long num, String supplierId) {
        Page<Product> page = lambdaQuery()
                .eq(Product::getSupplierId, Integer.parseInt(supplierId))
                .page(new Page<>(current, num));
        long total = page.getTotal();
        List<Product> productList = page.getRecords();
        PageDTO pageDTO = new PageDTO();
        pageDTO.setList(productList);
        pageDTO.setTotalNum(total);
        return Result.ok(pageDTO);
    }
}
